package com.app.micaihu.view.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.view.login.activity.PhoneCodeActivity;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;


/**
 * Created by Guo on 2016/7/22.
 * 更改手机
 */
public class ChangePhoneActivity extends BaseOldActivity implements View.OnClickListener {

    private EditText etCurrentPhoneNum;
    private ImageView ivInputCancel1;
    private EditText etNewPhoneNum;
    private ImageView ivInputCancel2;
    private TextView tvNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_changephone);
        initView();
        initListener();
    }

    private void initView() {
        setTitle("更换手机号");
        etCurrentPhoneNum = (EditText) findViewById(R.id.et_currentphonenum);
        ivInputCancel1 = (ImageView) findViewById(R.id.iv_input_cancel1);
        etNewPhoneNum = (EditText) findViewById(R.id.et_newphonenum);
        ivInputCancel2 = (ImageView) findViewById(R.id.iv_input_cancel2);
        tvNext = (TextView) findViewById(R.id.tv_next);

        tvNext.setEnabled(false);
    }

    private void initListener() {
        etCurrentPhoneNum.setOnFocusChangeListener(onFocusChangeListener);
        etNewPhoneNum.setOnFocusChangeListener(onFocusChangeListener);
        etCurrentPhoneNum.addTextChangedListener(mTextWatcher);
        etNewPhoneNum.addTextChangedListener(mTextWatcher);
        ivInputCancel1.setOnClickListener(this);
        ivInputCancel2.setOnClickListener(this);
        tvNext.setOnClickListener(this);

    }

    /**
     * 这对于edittext的 焦点监听
     */
    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            LinearLayout parent = (LinearLayout) v.getParent();
            if (parent == null) return;
            LinearLayout parent1 = (LinearLayout) parent.getParent();

            if(parent1 == null) return;
            if (hasFocus && v != null) {
                parent1.getChildAt(1).setVisibility(View.VISIBLE);
            } else {
                parent1.getChildAt(1).setVisibility(View.GONE);
            }

        }
    };

    /**
     * 文本监听
     */
    TextWatcher mTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (etNewPhoneNum == null || etCurrentPhoneNum == null) {
                ToastUtils.showText("请重新打开本页面");
                return;
            }
            if (!TextUtils.isEmpty(etNewPhoneNum.getText().toString().trim())
                    && !TextUtils.isEmpty(etCurrentPhoneNum.getText().toString().trim())) {
                tvNext.setEnabled(true);
            } else {
                tvNext.setEnabled(false);
            }
        }
    };

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.iv_input_cancel1:
                cleanContent1();
                break;
            case R.id.iv_input_cancel2:
                cleanContent2();
                break;
            case R.id.tv_next:
                commit();
                break;


        }
    }

    /**
     * 提交数据
     */
    private void commit() {

        if (etCurrentPhoneNum == null || etNewPhoneNum == null) {
            ToastUtils.showText("程序异常,请重新打开页面");
            return;
        }
        final String phoneNumber = etCurrentPhoneNum.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastUtils.makeText("请输入当前绑定手机号");
            return;
        }

        final String phoneNewNumber = etNewPhoneNum.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNewNumber)) {
            ToastUtils.makeText("请输入新手机号");
            return;
        }

        if(!UserInforManager.getInstance().isLogin()){
            ToastUtils.makeText("请重新登录");
            return;
        }

        if(request_state) return;
        //Map<String,String> params = new HashMap<>();
        ParamMap params = new ParamMap();
        if(UserInforManager.getInstance().isLogin()){
            params.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }else{
            params.putEncode("uid", "0");
        }

        params.putEncode("type",TypeConstant.CHANGE_PHONE);
        params.putEncode("mobile",etCurrentPhoneNum.getText().toString().trim());
        params.putEncode("newMobile",etNewPhoneNum.getText().toString().trim());
        //HttpUtils.ParmsMD5Encryption(params);
        HttpUtils.ParmsMapMD5(params);

        addPostRequest(URIContant.CHECK_MOBILE, new TypeToken<DataBean>() {
        }.getType(), params, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                request_state = true;
                DialogUtils.getInstance().showProgressDialog(ChangePhoneActivity.this,"正在提交");
            }

            @Override
            public void onError(VolleyError error) {
                request_state = false;
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
            }

            @Override
            public void onSuccess(DataBean response) {
                if(!response.noError()){
                    DialogUtils.getInstance().dismissProgressDialog();
                    ToastUtils.makeText(response.getMsg());
                }else{
                    Intent intent = new Intent(ChangePhoneActivity.this, PhoneResgiterCodeActivity.class);
                    intent.putExtra("newphone",etNewPhoneNum.getText().toString().trim());
                    intent.putExtra("phone",etCurrentPhoneNum.getText().toString().trim());
                    intent.putExtra(TypeConstant.ACTION_TYPE,TypeConstant.CHANGEPHONE_ACTION);

                    DialogUtils.getInstance().dismissProgressDialog();
                    startActivityForResult(intent,Config.ResultCode.REQUESTCODE_1);
                }

                request_state = false;

            }
        });

    }

    /**
     * 清除文本内容
     */
    private void cleanContent1(){
       if(etCurrentPhoneNum != null){
           etCurrentPhoneNum.setText("");
       }
    } private void cleanContent2(){
       if(etCurrentPhoneNum != null){
           etNewPhoneNum.setText("");
       }
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        if (requestCode == Config.ResultCode.REQUESTCODE_1 && resultCode == RESULT_OK) {
            setResult(resultCode);
            onBackPressed();
        }
    }
}
